<template>
  <div class="_wz_screeningProgramAdd">
    <Card dis-hover :bordered="true" style="margin:0 0 10px;">
      <p slot="title">基本信息</p>
      <Form ref="formAdd" :model="formData" label-position="right" :label-width="100" :rules="ruleValidate" class="_wz_hiddenTroubleAdd_form">
        <Row>
          <Col span="12">
            <FormItem label="排查计划" prop="riskPlanName">
              <i-input v-model="formData.riskPlanName" placeholder="请填写排查计划" clearable />
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="运输企业" prop="deptUuid">
              <i-select v-model="formData.deptUuid" filterable placeholder="请选择运输企业" clearable @on-change="screeningCascade">
                <Option v-for="item in subDeptList" :value="item.uuid" :key="item.uuid">{{ item.deptName }}</Option>
              </i-select>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="排查周期" prop="riskPlanCycleUuid">
              <i-select v-model="formData.riskPlanCycleUuid" filterable placeholder="请选择排查周期" clearable>
                <Option v-for="item in riskCycleList" :value="item.uuid" :key="item.uuid">{{ item.riskCycleName }}</Option>
              </i-select>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="排查时间" prop="dateSearchRange">
              <DatePicker v-model="formData.dateSearchRange" split-panels :options="dateSearchRangeOption" type="daterange" placeholder="请选择起始日期" style="width: 100%;"></DatePicker>
            </FormItem>
          </Col>
        </Row>
      </Form>
    </Card>
    <Card dis-hover :bordered="true">
      <p slot="title">隐患部位</p>
      <p slot="extra">
        <Button type="primary" @click="addTableData">添加</Button>
        <Button type="primary" @click="batchAddTableData">批量添加</Button>
      </p>
      <wzTbale ref="wzTbale" :tableData="tableData"></wzTbale>
    </Card>

    <div class="demo-drawer-footer" style="z-index: 99;">
      <Button style="margin-right: 8px" @click="$emit('closeFun',false)">取消</Button>
      <Button type="primary" @click="addSubmit('formAdd')">提交</Button>
    </div>
    <Spin size="large" fix v-if="spinShow"></Spin>



<!--添加-->
    <Drawer :title="formTitle" v-model="formOperation" width="1040" :mask-closable="false" :draggable="true" :styles="formOperationStyles">
      <partFebruaryAdd v-if="formOperation" :selectData="formSelectData" :parentFormData="formData"  @childCloseFun="childCloseFun"></partFebruaryAdd>
    </Drawer>


<!--批量-->
    <Drawer :title="formTitle" v-model="batchFormOperation" width="1040" :mask-closable="false" :draggable="true" :styles="formOperationStyles">
      <batchPartFebruaryAdd v-if="batchFormOperation" :parentFormData="formData"  @batchChildCloseFun="batchChildCloseFun"></batchPartFebruaryAdd>
    </Drawer>
  </div>
</template>
<script>
import wzTbale from "../../components/table/table";
import partFebruaryAdd from "./partFebruaryAdd";//排查项添加
import batchPartFebruaryAdd from "./batchPartFebruaryAdd";//排查项添加
export default {
  components: {
    wzTbale,//列表
    partFebruaryAdd,//排查项添加
    batchPartFebruaryAdd,
  },
  props: ['selectData'],//接收来自父组件的数据
  data() {
    return {
      formOperationStyles: {//表单左侧移出css
        height: 'calc(100% - 55px)',
        overflow: 'auto',
        paddingBottom: '53px',
        position: 'static'
      },
      dateSearchRangeOption: {
        disabledDate (date) {
          return date && date.valueOf() < Date.now() - 86400000;
        }
      },
      riskCycleList:[],//排查周期
      subDeptList:[],//企业
      spinShow:false,//本页加载
      ruleValidate: {//正则
        deptUuid: [
          {required: true, message: '请选择运输企业', trigger: 'blur'}
        ],
        riskPlanName: [
          {required: true, message: '请填写排查计划', trigger: 'blur'}
        ],
        riskPlanCycleUuid: [
          {required: true, message: '请选择排查周期', trigger: 'blur'}
        ],
        dateSearchRange: [{
          type: 'array',
          required: true,
          message: '请输入起止日期',
          fields: {
              0: {type: 'date', required: true, message: '请输入起止日期'},
              1: {type: 'date', required: true, message: '请输入起止日期'}
            }
          }],
      },
      formData: {},


      tableData: {
        method: 'post',//请求方式
        where: {},//搜索条件
        height: 'auto',//表格高度 auto
        page: false,//分页是否使用
        noHighlightRow:true,//  本地数据操作 不是使用行内选择
        columns: [//表头数据
          {type: 'index', width: 70, align: 'center', title: '序号'},
          {title: '隐患部位', minWidth:140, key: 'riskPositionName'},
          {title: '隐患类型', minWidth:140, key: 'riskPositionType', render: (h, params) => {
              //  （1：基础管理、2：设备设施、3：作业活动）
              if (params.row.riskPositionType == 1) {
                return h('Tag', {props: {type: 'dot',color: 'success'}}, '基础管理')
              } else if (params.row.riskPositionType == 2) {
                return h('Tag', {props: {type: 'dot',color: 'primary'}}, '设备设施')
              } else if (params.row.riskPositionType == 3) {
                return h('Tag', {props: {type: 'dot',color: 'warning'}}, '作业活动')
              }
            }
          },
          {title: '排查渠道', width:140, key: 'riskPlanItemType', render: (h, params) => {
              //  1：人员排查，2：车辆排查
              if (params.row.riskPlanItemType == 1) {
                return h('Tag', {props: {type: 'dot',color: 'success'}}, '人员排查')
              } else if (params.row.riskPlanItemType == 2) {
                return h('Tag', {props: {type: 'dot',color: 'primary'}}, '车辆排查')
              }
            }
          },
          {title: '排查人员', minWidth: 260, key: 'riskPlanItemCheckName'},
          {
            title: '操作', fixed: 'right', width:120,
            render: (h, params) => {
              let that = this;
              var operationButtons = [];
              operationButtons.push(
                h('span', {
                  style: {"color": "#2d8cf0", "cursor": "pointer"},
                  on: {
                    click: () => {
                      var that = this;
                      that.formTitle = "修改";
                      var data = JSON.parse(JSON.stringify(params))
                      data.row.index = data.index + 1;
                      that.formSelectData = data.row;
                      that.formSelectData.riskPlanItemCheckUuids = that.formSelectData.riskPlanItemCheckUuid.split(',')
                      that.formOperation = true;

                    }
                  }
                },'修改' )
              )
              operationButtons.push(h('Divider', {props: {type: 'vertical',}}, ''))
              operationButtons.push(
                h('span', {
                  style: {"color": "#2d8cf0", "cursor": "pointer"},
                  on: {
                    click: () => {
                      that.tableData.dataList.splice(params.index,1);
                    }
                  }
                },'删除')
              )

              return operationButtons;
            }
          },
        ],
        dataList:[]
      },
      formTitle:'',//排查添加
      formOperation:false,//隐患部位
      batchFormOperation:false,
      formSelectData:{},
    }
  },
  beforeCreate() {//beforeCreate创建前状态

  },
  created() {//created创建完毕状态

  },
  beforeMount() {//beforeMount挂载前状态   DOM 元素然后塞入页面的过程

  },
  mounted() {//mounted 挂载结束状态
    var that = this;
    //运输企业
    that.axios.post(that.apiUrl.coreDeptCoreDeptList, {}).then(res => {
      if (!!res) {
        that.subDeptList = res.data.data;
        if (!that.selectData.id) {
          that.formData.deptUuid = that.subDeptList[0].uuid;
          that.screeningCascade(that.formData.deptUuid)
        }
      }
    }).catch(err => {
      console.log("失败", err)
    })
    that.formData = that.selectData;
    that.$set(that.formData, 'dateSearchRange', [!!that.formData.riskPlanStartDate?new Date(that.formData.riskPlanStartDate) : '' , !!that.formData.riskPlanEndDate ? new Date(that.formData.riskPlanEndDate) : ''])//赋值
    // that.$set(that.formData, 'dateSearchRange', [!!that.formData.riskPlanStartDate?new Date(that.formData.riskPlanStartDate):new Date(),!!that.formData.riskPlanEndDate?new Date(that.formData.riskPlanEndDate):new Date()])//赋值

    //企业级联
    that.screeningCascade(that.formData.deptUuid);

    // 修改时 tbale 赋值
    if(!!that.selectData.id){
      that.axios.post(that.apiUrl.riskPlanRiskPlanItemList, {riskPlanUuid:that.formData.uuid}).then(res => {
        if (!!res) {
          that.tableData.dataList = res.data.data;
        }
      }).catch(err => {
        console.log("失败", err)
      })
    }


    //
  },
  methods: {//执行的方法
    //table添加
    addTableData() {
      var that = this;
      that.formTitle = "添加";
      that.formSelectData = {};
      that.formOperation = true;
    },
    batchAddTableData() {
      var that = this;
      that.formTitle = "添加";
      that.batchFormOperation = true;
    },
    //排查周期 级联
    screeningCascade(data){
      let that = this;
      that.riskCycleList = [];

      if(!!data){
        //排查周期
        that.axios.post(that.apiUrl.riskPlanRiskCycleList, {deptUuid:that.formData.deptUuid}).then(res => {
          if (!!res) {
            that.riskCycleList = res.data.data;
          }
        }).catch(err => {
          console.log("失败", err)
        })
      }
    },
    //提交表单
    addSubmit(data) {
      let that = this;


      that.$refs[data].validate((valid) => {
        if (valid) {//正则判断使用
          if(that.tableData.dataList.length == 0){
            that.$Message.error('请填写隐患部位');
            return false;
          }
          that.formData.riskPlanItemList = that.tableData.dataList;
          that.formData.riskPlanStartDate = that.public.timeFormatting(that.formData.dateSearchRange[0], "yyyy-MM-dd");
          that.formData.riskPlanEndDate = that.public.timeFormatting(that.formData.dateSearchRange[1], "yyyy-MM-dd");
          that.spinShow = true;//显示加载
          that.axios.post(that.apiUrl.riskPlanRiskPlanSaveOrUpdate, that.formData).then(res => {
            that.spinShow = false;
            if (!!res) {
              that.$Message.success("操作成功");
              that.$emit("closeFun", true)
            }
          }).catch(err => {
            console.log('失败', err);
          })
        } else {
          that.$Message.error('请正确填写表单');
        }
      })
    },
    //
    childCloseFun(type,data) {
      var that = this;
      if (type) {//添加修改 刷新表单
        if(!!data.index){
          that.$set(that.tableData.dataList, data.index - 1, data)
        }else{
          that.tableData.dataList.push(data)
        }
      }
      that.formOperation = false;
    },
    batchChildCloseFun(type,data) {
      var that = this;
      if (type) {//添加修改 刷新表单
        data.riskPositionUuidList.forEach((k,i)=>{
          let obj = Object.assign( JSON.parse(JSON.stringify(data)), k);
          that.tableData.dataList.push(obj)
        })
      }
      that.batchFormOperation = false;
    },

  },
  watch: {//监听

  },
  beforeUpdate() {//beforeUpdate 更新前状态

  },
  updated() {//updated 更新完成状态

  },
  beforeDestroy() {//beforeDestroy 销毁前状态

  },
  destroyed() {//destroyed 销毁完成状态

  }
}
</script>
<style lang="less">
._wz_screeningProgramAdd {
  height: 100%;
}
</style>
